﻿using System;
using System.Collections.Generic;

using JetBrains.DocumentModel;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;

namespace FinlogiK.ReSharperContrib
{
	internal sealed class AddStaticQualifierDaemonStageProcess : IDaemonStageProcess
	{
		#region Fields

		private readonly IDaemonProcess _process;

		#endregion

		#region Constructors

		internal AddStaticQualifierDaemonStageProcess(IDaemonProcess process)
		{
			this._process = process;
		}

		#endregion

		#region IDaemonStageProcess Members

		public void Execute(Action<DaemonStageResult> commiter)
		{
			if (!this._process.InterruptFlag)
			{
				ICSharpFile file = this._process.ProjectFile.GetPsiFile(CSharpLanguageService.CSHARP) as ICSharpFile;

				if (file != null)
				{
					List<HighlightingInfo> highlights = new List<HighlightingInfo>();

					RecursiveElementProcessor<IReferenceExpression> processor = new RecursiveElementProcessor<IReferenceExpression>(referenceExpression =>
					{
						if (ArrangeStaticQualifierHelper.IsReferenceToStaticMemberWithoutQualifier(referenceExpression))
						{
							DocumentRange documentRange = referenceExpression.GetNavigationRange();
							highlights.Add(new HighlightingInfo(documentRange, new AddStaticQualifierHighlight(referenceExpression)));
						}
					});

					file.ProcessDescendants(processor);
					commiter.Invoke((new DaemonStageResult(highlights)));
				}
			}
		}

		#endregion
	}
}